//
// Created by void on 24-1-8.
//

#include "ChannelMap.h"

struct ChannelMap *channelMapInit(int size) {
    struct ChannelMap* map = (struct ChannelMap*)malloc(sizeof(struct ChannelMap));
    map->size = size;
    map->list = (struct Channel**)malloc(size * sizeof (struct Channel*));
    return map;
}

void channelMapClear(struct ChannelMap *map) {
    if(map) {
        for(int i = 0; i < map->size; ++i) {
            if(map->list[i]) {
                free(map->list[i]);
            }
        }
        free(map->list);
        map->list = NULL;
    }
    map->size = 0;
}

bool makeMapRoom(struct ChannelMap* map, int newSize, int unitSize) {
    if(map->size < newSize) {
        int curSize = map->size;
        while(curSize < newSize) {
            curSize *= 2;
        }
        struct Channel** temp = realloc(map->list, curSize * unitSize);
        if(!temp) {
            return false;
        }
        map->list = temp;
        memset(&map->list[map->size], 0, (curSize - map->size) * unitSize);
        map->size = curSize;
    }
    return true;
}
